<template>
  <div>
    <h3 class="title">
      <span v-if="formDis ===false && isEdit === false">新增轮播图</span>
      <span v-if="isEdit === true">编辑轮播图</span>
      <span v-if="formDis === true">查看详情</span>
    </h3>
    <el-form
      ref="carouselForm"
      :disabled="formDis"
      :model="carouselForm"
      :rules="rules"
      label-width="120px"
      class="demo-ruleForm"
      style="margin-top: 20px;">
      <el-form-item label="轮播图组名称" prop="name">
        <el-col :span="6" >
          <el-input v-model="carouselForm.name" maxlength="50" placeholder="请填写轮播图组名称" />
        </el-col>
      </el-form-item>
      <!-- {{ carouselForm.carouselImages }} -->
      <el-form-item label="图文列表管理" class="add_tip">
        <el-col :span="8" >
          <el-button :disabled="carouselForm.carouselImages.length >= 5" type="primary" size="mini" @click="addCarousel()">增加一条</el-button>
        </el-col>
      </el-form-item>
      <el-form-item>
        <el-col :span="20">
          <el-table
            v-loading="listLoading"
            v-if="carouselForm.carouselImages.length"
            :data="carouselForm.carouselImages"
            element-loading-text="加载中请稍后"
            border
            fit
            highlight-current-row>
            <el-table-column align="center" label="图片顺序">
              <template slot-scope="scope">
                {{ scope.row.sort }}
              </template>
            </el-table-column>
            <el-table-column align="center" label="图片">
              <template slot-scope="scope">
                <img :src="scope.row.imageUrl" class="img">
              </template>
            </el-table-column>
            <el-table-column align="center" label="图片名称">
              <template slot-scope="scope">
                {{ scope.row.imageName }}
              </template>
            </el-table-column>
            <!-- <el-table-column align="center" label="商品名称">
              <template slot-scope="scope">
                {{ scope.row.goodsName }}
              </template>
            </el-table-column> -->
            <el-table-column align="center" label="操作" width="160">
              <template slot-scope="scope">
                <el-button type="primary" size="mini" @click="editCarousel(scope.$index)">编辑</el-button>
                <el-button type="danger" size="mini" @click="delCarousel(scope.$index)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-form-item>
      <!-- {{ carouselForm }} -->
      <el-form-item label="使用状态" prop="status">
        <el-col :span="8" >
          <el-select v-model="carouselForm.status" placeholder="请选择使用状态">
            <el-option :value="0" label="停用"/>
            <el-option :value="1" label="启用"/>
          </el-select>
        </el-col>
      </el-form-item>
      <el-form-item>
        <!-- 编辑 -->
        <el-button v-preventReClick v-if="isEdit" type="primary" @click="submitForm('carouselForm')">确定</el-button>
        <!-- 新增 -->
        <el-button v-preventReClick v-if="!isEdit && !formDis" type="primary" @click="submitForm('carouselForm')">确定</el-button>
        <!-- 取消 -->
        <el-button v-preventReClick @click="$router.go(-1)">关闭</el-button>
      <!-- <el-button @click="resetForm('carouselForm')">重置</el-button> -->
      </el-form-item>

    </el-form>
    <!-- <el-button v-preventReClick v-if="formDis" style="margin:0 0 40px 40px" type="primary" @click="$router.go(-1)">返回</el-button> -->
    <!-- <addcarousel :carousel-visible.sync="carouselVisible" :receive-list-data.sync="receiveListData"/> -->
    <addcarousel
      :carousel-visible.sync="carouselVisible"
      :edit-data.sync="editData"
      :edit-index.sync="editIndex"
      @updateFn="updatereceiveList"
    />
  </div>
</template>

<script>
import config from '@/utils/config';
import Tinymce from '@/components/Tinymce'
import { Message } from 'element-ui'
// import mixin from '@/mixin'

import addcarousel from '@/components/carousel/add.vue'
import carouselList from '@/components/carousel/list'
import { carouselAdd, checkCarousel, carouselEdit } from '@/api/productCarousel'

export default {
  components: { addcarousel, carouselList },
  // mixins: [mixin],
  data() {
    return {
      momList: [],
      // picUrlCurPath: '',
      imgsCurData: {
        url: '',
        picName: ''
      },
      isDiscountCheck: [false, false, false, false],
      isRebateChecks: [false, false, false, false],
      isUpload: true, // 控制轮播图按钮
      carouselForm: {
        name: '', // 商品名称
        status: 0,
        carouselImages: []
      },
      discountList: [],
      list: [],
      receiveListData: {},
      listLoading: false,
      teacher: [],
      isWatch: false,
      rules: {
        name: [
          { required: true, message: '请填写商品名称', trigger: 'blur' }
        ],
        status: [
          { required: true, message: '请选择使用状态', trigger: 'change' }
        ]
      },
      fileList: [],
      actionUrl: config.BaseUrl + '/storage/create',
      uploadData: {
        key: '',
        token: ''
      },
      formDis: false,
      tinymceDis: false,
      isEdit: false,
      selectShow: false,
      myProduct: {},
      // 对应<请选择讲师下拉菜单>查询教师信息列表时，把status为1的教师获取出来
      listQuery: {
        pageNum: 0,
        pageSize: 1000,
        status: 1
      },
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7;
        }
      },
      isDisabled: false,
      // 轮播图 - 添加一条显示隐藏
      carouselVisible: false,
      editData: {},
      editIndex: -1
    }
  },
  computed: {
    ruleForm: function() {
      return this.$store.getters.ruleForm
    }
  },
  watch: {
    // receiveListData: {
    //   handler: function(nowVal, oldVal) {
    //     console.log('receiveListData数据变了', nowVal)
    //     this.carouselForm.carouselImages.push(nowVal)
    //   },
    //   deep: true
    // }
  },
  created() {
    // 获取美妈类别 并且判断谁为选中，百分比为多少
    // this.getMomList()
    // 获取折扣信息
    // this.getConstantPercent()
  },
  mounted() {
    const _self = this;
    // console.log('this.$route.query:', JSON.stringify(this.$route.query))
    if (this.$route.query && JSON.stringify(this.$route.query) !== '{}') {
      console.log(this.$route.query)
      this.isEdit = this.$route.query.hasOwnProperty('isEdit') ? _self.$route.query.isEdit : false;
      this.formDis = Boolean(this.$route.query.isLook)
      this.tinymceDis = Boolean(this.$route.query.isLook)
      const a = this.$route.query
      if (a.hasOwnProperty('isLook')) {
        // this.dataToHtml(a)
        this.getProductListFn(a.id)
        this.selectShow = true
        delete a.isLook;
      }
      if (a.hasOwnProperty('isEdit')) {
        // this.dataToHtml(a)
        // this.getTeacherList()
        this.getProductListFn(a.id)
        delete a.isEdit;
      }
    //   this.$store.dispatch('AddlistenForm', this.$route.query).then(() => {
    //   }).catch((err) => {
    //     Message.error(err.err)
    //   })
    } else { // 新增
    //   this.getTeacherList()
    //   this.$store.dispatch('resetFunc').then(() => {
    //   }).catch((err) => {
    //     Message.error(err.err)
    //   })
    }
    // this.uploadData.token = GetQiniuToken().uploadToken
  },
  methods: {
    // 排序
    listSort(list, key) {
      return list.sort(function(a, b) {
        const x = a[key]
        const y = b[key]
        return ((x < y ? -1 : (x > y) ? 1 : 0))
      })
    },
    // 删除图片列表的 其中一个
    delCarousel(index) {
      this.$confirm('您确定要删除此商品？', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.carouselForm.carouselImages.splice(index, 1)
        Message.success('已经移除此商品')
      })
    },
    // 编辑图片列表的 其中一个
    editCarousel(index) {
      this.editData = Object.assign({}, this.carouselForm.carouselImages[index])
      // this.editData = data
      this.carouselVisible = true
      this.editIndex = index
    },
    updatereceiveList(data, index) {
      // console.log('-------', index, '--------')
      const obj = Object.assign({}, data)
      if (index === -1) { // 如果为 -1 就是新增
        // alert('新增', index)
        if (obj.id) obj.id = ''
        if (obj.carouselId) obj.carouselId = ''
        this.carouselForm.carouselImages.push(obj)
      } else { // 其他就是编辑
        // alert('编辑', index)
        this.$set(this.carouselForm.carouselImages, index, obj)
        // this.carouselForm.carouselImages[index] = obj
      }
      this.listSort(this.carouselForm.carouselImages, 'sort')
    },
    addCarousel() {
      this.editIndex = -1 // 如果为 -1 就是新增
      this.carouselVisible = true
    },
    request(data) {
      this.isEdit ? carouselEdit(data).then(response => {
        if (Number(response.code) === 200) {
          Message.success('编辑成功')
          this.$router.go(-1);
        } else {
          Message.error(response.message + '-' + response.data)
        }
      }) : carouselAdd(data).then(response => {
        if (Number(response.code) === 200) {
          Message.success('新增成功')
          this.$router.push('carouselList');
        } else {
          Message.error(response.message + '-' + response.data)
        }
      });
    },
    getProductListFn(id) {
      const obj = { id }
      console.log(obj)
      checkCarousel(obj).then(res => {
        if (res.code === '200') {
          console.log('--------', res)
          this.carouselForm = res.data
        } else {
          Message.error(res.message + res.data)
        }
      })
    },
    toEdit() {
      carouselEdit(this.carouselForm).then(res => {
        console.log(res)
        if (res.code === '200') {
          Message.success('更新成功')
          this.$router.go(-1)
        }
      })
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (!this.carouselForm.carouselImages.length) {
            Message.error('请添加图文列表')
            return false
          }
          console.log(this.carouselForm)
          this.request(this.carouselForm)
        } else {
          // this.validateError()
          return false;
        }
      });
    },
    resetForm(formName) {

    }

  }
}
</script>

<style lang="scss" scoped>
      .fl{
      float: left;
      }
      .fr {
      float: right
      }
      hr{
      border-top: 1px solid #ddd;
      margin: 20px 0;
      }
      .title{
      margin: 30px;
      color:#333;

      }
      .el-table__header tr,
      .el-table__header th {
      padding: 0;
      height: 30px !important;
      }
      .el-table__body tr,
      .el-table__body td {
      padding: 0 !important;
      height: 30px !important;
      }
      .el-table td, .el-table th {
      padding: 0 !important;
      }
      .tipBox{
      margin-top: 40px;
      margin-left: 10px;
      }
      .thumbnail{
      width: 302px;
      height: 200px;
      border: 1px solid #eee;
      border-radius: 5px;
      display: flex;
      // flex-item-align: center;
      }

      .thumbnail .img{
      width: 100px;
      height: 50px;
      }
      .uploadBox{
      width: 100%;
      }
      .btn_clear{
      margin-top: 4px;
      padding: 10px 30px;
      }

      .productName{
      width:300px
      }

      .table{
      width: 100%;
      border-collapse: collapse;
      border-spacing: 0;
      }
      .table td{
      border: 1px solid #ddd;
      padding: 5px 10px;
      }

      .tip {
      color: red;
      }
      .tin_box {
      border: 1px solid #ddd;
      padding: 0 10px 0 10px;
      color:#666;
      }
      .line{
      text-align: center;
      }

      .el-upload-list, .el-form-item__content{
      display: none;
      }
      .img{
        width: 100px;
        height: 50px;
      }
</style>
